

package ro.ase.catalog.mail.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.mail.javamail.MimeMessagePreparator;
import ro.ase.catalog.mail.IEmailSender;

import javax.mail.internet.MimeMessage;
import java.util.ArrayList;
import java.util.List;


public class EmailSenderImpl implements IEmailSender { 
    @Autowired
    private JavaMailSender mailSender;
    
    public void sendEmail(String from, List<String> recipients, String subj, String text) {
        
        final String fm = from;
        final String s = subj;
        final String tpl = text;
       
        for(final String to : recipients){

            Runnable thread=new Runnable(){
                public void run(){
                    try {
                        mailSender.send(new MimeMessagePreparator() {
                            public void prepare(MimeMessage mimeMessage) throws Exception {
                                MimeMessageHelper helper = new MimeMessageHelper(mimeMessage,"UTF-8");
                                if(fm!=null)  helper.setFrom(fm);
                                else helper.setFrom("catalog-noreply@gmail.com");
                                if(s!=null) helper.setSubject(s);
                                else helper.setSubject("no subject");
                                if(tpl!=null) helper.setText(tpl);
                                else helper.setText("no text");
                                helper.setTo(to);
                            }
                        });
                    }
                    catch (MailException ex) {
                        // simply log it and go on...
                        System.err.println(ex.getMessage());            
                    }
                }
            };
            new Thread(thread).start();                    
        }
    }
    
    public void sendEmail(String from, String recipient, String subj, String text) {
        List recipients = new ArrayList <String>();
        recipients.add(recipient); 
        
        sendEmail(from, recipients, subj, text);
    }    
}

